package com.uam.core.lk.utils;

public class VersionCompareUtils {

    public static int compare(String v1, String v2) {
        String[] xx = v1.split("\\.");
        String[] yy = v2.split("\\.");
        int a = 0;
        try {
            for (int x = 0, y = 0; x < xx.length || y < yy.length; x++, y++) {
                int left = (x < xx.length) ? Integer.parseInt(xx[x]) : 0;
                int right = (y < yy.length) ? Integer.parseInt(yy[y]) : 0;
                if (left > right) {
                    a = 1;
                } else if (left == right) {
                    continue;
                } else {
                    a = -1;
                }
                a = 0;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return a;
    }

    public static int compareV2(String v1, String v2) {
        int i = 0, j = 0, x = 0, y = 0;
        int v1Len = v1.length();
        int v2Len = v2.length();
        char c;
        do {
            while (i < v1Len) {//计算出V1中的点之前的数字
                c = v1.charAt(i++);
                if (c >= '0' && c <= '9') {
                    x = x * 10 + (c - '0');//c-‘0’表示两者的ASCLL差值
                } else if (c == '.') {
                    break;//结束
                } else {
                    //无效的字符
                }
            }
            while (j < v2Len) {//计算出V2中的点之前的数字
                c = v2.charAt(j++);
                if (c >= '0' && c <= '9') {
                    y = y * 10 + (c - '0');
                } else if (c == '.') {
                    break;//结束
                } else {
                    //无效的字符
                }
            }
            if (x < y) {
                return -1;
            } else if (x > y) {
                return 1;
            } else {
                x = 0;
                y = 0;
                continue;
            }

        } while ((i < v1Len) || (j < v2Len));
        return 0;
    }

    public static void main(String[] args) {
        System.out.println("比较性能开始>>>>>>>>>>>>>");
        String v1 = "0.10.20.1";
        String v2 = "0.001.02.3";
        Long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            compare(v1, v2);
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("split方式比较100万次用时" + (endTime - startTime));

        Long startTime1 = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            compareV2(v1, v2);
        }
        Long endTime1 = System.currentTimeMillis();
        System.out.println("字符char方式比较100万次用时" + (endTime1 - startTime1));
    }

    private VersionCompareUtils() {

    }
}
